package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.config.RabbitmqConfig;
import cn.itsource.hrm.jwt.JwtUtils;
import cn.itsource.hrm.util.*;
import cn.itsource.hrm.client.RedisClient;
import cn.itsource.hrm.domain.Sso;
import cn.itsource.hrm.domain.VipBase;
import cn.itsource.hrm.mapper.SsoMapper;
import cn.itsource.hrm.mapper.VipBaseMapper;
import cn.itsource.hrm.service.ISsoService;
import cn.itsource.hrm.util.encrypt.MD5;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author yhptest
 * @since 2020-06-30
 */
@Service
public class SsoServiceImpl extends ServiceImpl<SsoMapper, Sso> implements ISsoService {

    @Autowired
    private SsoMapper ssoMapper;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private VipBaseMapper vipBaseMapper;

    @Override
    public AjaxResult login(Map<String, Object> params) {
        //1 接收参数
        String username = (String) params.get("username"); //username phone email
        String password = (String) params.get("password");
        Integer userType = Integer.valueOf(params.get("userType").toString());
        //2 校验 手机是否被注册 短信验证码
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)
                || userType==null)
            return AjaxResult.me().setSuccess(false).setMessage("请输入相关参数！");
        //判断用户是否存在
        Sso sso = ssoMapper.login(params);
        if (sso == null)
            return AjaxResult.me().setSuccess(false).setMessage("请输入正确用户名或密码！");
        //校验密码是否正确
        String inputPwd = MD5.getMD5(password + sso.getSalt());
        if (!sso.getPassword().equals(inputPwd))
            return AjaxResult.me().setSuccess(false).setMessage("请输入正确用户名或密码！");

        //3 token构造 redis token:jwt
        //3.1 获取私钥
        PrivateKey privateKeyPath = RsaUtils.getPrivateKey(SsoServiceImpl.class.getClassLoader()
                        .getResource("hrm_auth_rsa").getFile());
        //3.2 产生jwttoken
        String jwtToken = JwtUtils.generateTokenExpireInMinutes(sso, privateKeyPath, 30);
        String token = UUID.randomUUID().toString();
        //3.3 保存到redis
        Map<String,Object> paramsTmp = new HashMap<>();
        paramsTmp.put("key",token);
        paramsTmp.put("value",jwtToken);
        paramsTmp.put("expire",30*60);
        redisClient.add(paramsTmp);
        //3.4 返回结果
        Map<String,Object> result = new HashMap<>();
        sso.setPassword(null); //前端吧不需要密码
        sso.setSalt(null);
        result.put("sso",sso);
        result.put("token",token);
        return AjaxResult.me().setResultObj(result);
    }

    public static void main(String[] args) {
        System.out.println(MD5.getMD5("1" + "IUZNuePMO9M2WjpRDobmkumphfW5SVnx"));
    }
        @Override
    public AjaxResult register(Map<String, Object> params) {
        //1 接收参数
        String mobile = (String) params.get("mobile");
        String password = (String) params.get("password");
        String smsCode = (String) params.get("smsCode");
        String email = (String) params.get("email");
        //2 校验 手机是否被注册 短信验证码
        if (StringUtils.isBlank(mobile)|| StringUtils.isBlank(password)
                ||StringUtils.isBlank(smsCode))
            return AjaxResult.me().setSuccess(false).setMessage("请输入相关参数！");
        EntityWrapper<Sso> wrapper = new EntityWrapper<>();
        wrapper.eq("phone",mobile);
        wrapper.eq("userType", UserType.USERTYPE_VIP); //魔鬼数字 同一个手机号可能有两个类型用户（会员，管理员）
        List<Sso> ssos = ssoMapper.selectList(wrapper);
        if (ssos!=null && ssos.size()>0)
            return AjaxResult.me().setSuccess(false).setMessage("该账户已经被注册！");

        String code = redisClient.get(UserConstants.REGISTER_CODE_PREFIX + mobile);
        if (StringUtils.isBlank(code)||!(code.split(":")[0].equalsIgnoreCase(smsCode)))
           return AjaxResult.me().setSuccess(false).setMessage("请输入正确验证码！");
        //3 保存主表 t_sso
        Sso sso = new Sso();
        sso.setCreateTime(System.currentTimeMillis());
        sso.setPhone(mobile);
        sso.setUsername(mobile);
        sso.setNickName(StrUtils.getComplexRandomString(4));
        sso.setUserType(UserType.USERTYPE_VIP);
        sso.setSecLevel(0);
        //未激活-1 已激活1 已手机实名认证2 一个值表示多个状态-二进制表示法
        sso.setBitState(2L);
        String salt = StrUtils.getComplexRandomString(32);
        String secretyPwd = MD5.getMD5(password+salt);
        sso.setSalt(salt);
        sso.setPassword(secretyPwd);
        ssoMapper.insert(sso);
        //4 保存关联表 t_vip_base
        VipBase vipBase = new VipBase();
        vipBase.setCreateTime(System.currentTimeMillis());
        vipBase.setRegTime(System.currentTimeMillis());
        vipBase.setSsoId(sso.getId());
        // 手机0 pc为1 平板 2
        vipBase.setRegChannel(1);
        vipBase.setLevel(0);
        vipBase.setGrowScore(0);
        vipBaseMapper.insert(vipBase);
        //生成消息
        String message = "{\"phone\":"+mobile+",\"email\":"+email+"}";
        rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_FANOUT_INFORM,"",message);
        return AjaxResult.me();
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;
}
